package cn.bsuc.crm.interceptor;

import cn.bsuc.crm.entity.User;
import cn.bsuc.crm.util.*;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

import static cn.bsuc.crm.util.RedisConstants.LOGIN_TOKEN_TTL;

/**
 * @author : zhuoyuan
 * @date : 2022/10/8 19:46
 * @description :
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /*
      根据token验证登录身份
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html;charset=utf8");
        // 1.拿到token
        String token = request.getHeader("token");
        // 2.验证token是否有效
        if (!JwtUtils.checkToken(token)) {
            // 无效
            Result fail = Result.fail(Code.ERROR, "请先登录！");
            String json = JSON.toJSONString(fail);
            response.getWriter().print(json);
            return false;
        }
        // 3.验证token是否过期
        User user = JwtUtils.getUserByToken(token);
        String tokenKey= RedisConstants.LOGIN_TOKEN_KEY + user.getUserName();

        if (!stringRedisTemplate.hasKey(tokenKey)) {
            Result fail = Result.fail(Code.ERROR, "登录过期，请重新登录！");
            String json = JSON.toJSONString(fail);
            response.getWriter().print(json);
            return false;
        }

        UserHolder.saveUser(user);

        // 4.放行
        //重置token时间
        stringRedisTemplate.expire(tokenKey,LOGIN_TOKEN_TTL, TimeUnit.SECONDS);
        return true;
    }

}
